package com.hdey.utils;

import com.hdey.pojo.heng.TbUscUser;
import com.hdey.service.heng.TbUscPermissionService;
import com.hdey.service.heng.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Component
public class DbRealm extends AuthorizingRealm {

    @Resource
    private UserService service;
    @Resource
    private TbUscPermissionService permissionService;


    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        TbUscUser tbUscUser = (TbUscUser) principalCollection.getPrimaryPrincipal();
        List<String> perCodeList=permissionService.findPermCodeList(tbUscUser.getRoleId());
//        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermissions(perCodeList);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken Token) throws AuthenticationException {
        String loginName= (String) Token.getPrincipal();
        TbUscUser tbUscUser =null;
        try{
            tbUscUser =service.admin(loginName);
        }catch (Exception e){

        }
        System.out.println(tbUscUser);
        if (tbUscUser ==null){
            return null;
        }
        SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(tbUscUser, tbUscUser.getPassword(), this.getName());
        System.out.println(info);
        return info;
    }
}
